# -*- coding: UTF-8 -*-
from PySide6.QtWidgets import QDialog, QVBoxLayout, QTextEdit, QDialogButtonBox, QMessageBox


def delete_device(self):
    """删除选中的设备"""
    # 添加权限检查
    if not self.check_is_admin():
        QMessageBox.warning(self, "权限不足", "只有管理员可以删除设备,请点击右上角的个人中心登录")
        return
        
    selected_rows = []
    for row in range(self.table.rowCount()):
        checkbox_widget = self.table.cellWidget(row, 0)
        if checkbox_widget and checkbox_widget.layout().itemAt(0).widget().isChecked():
            selected_rows.append(row)

    if not selected_rows:
        QMessageBox.warning(self, "警告", "请选择要删除的设备")
        return

    reply = QMessageBox.question(
        self,
        "确认删除",
        f"确定要删除选中的 {len(selected_rows)} 个设备吗？",
        QMessageBox.Yes | QMessageBox.No,
        QMessageBox.No
    )

    if reply == QMessageBox.Yes:
        # 获取要删除的设备IP地址列表
        devices_to_delete = []
        for row in selected_rows:
            ip = self.table.item(row, 5).text()  # IP地址在第6列
            devices_to_delete.append(ip)

        # 从设备列表中删除设备
        self.devices = [device for device in self.devices if device["ip"] not in devices_to_delete]
        
        # 保存更新后的设备列表
        self.save_devices()
        
        # 更新筛选索引
        if self.filtered_indices:
            # 重新计算筛选索引
            self.apply_filter()
        else:
            # 如果没有筛选，直接更新表格
            self.update_table()


def delete_single_device(self, row, devices):
    """删除单个设备"""
    # 添加权限检查
    if not self.check_is_admin():
        QMessageBox.warning(self, "权限不足", "只有管理员可以删除设备,请点击右上角的个人中心登录")
        return
        

    if 0 <= row < len(devices):
        device = devices[row]
        reply = QMessageBox.question(
            self,
            "确认删除",
            f"确定要删除设备 {device['host']} ({device['ip']}) 吗？",
            QMessageBox.Yes | QMessageBox.No,
            QMessageBox.No
        )

        if reply == QMessageBox.Yes:
            # 从设备列表中删除设备
            self.devices = [d for d in self.devices if d["ip"] != device["ip"]]
            
            # 保存更新后的设备列表
            self.save_devices()
            
            # 更新筛选索引
            if self.filtered_indices:
                # 重新计算筛选索引
                self.apply_filter()
            else:
                # 如果没有筛选，直接更新表格
                self.update_table()


def select_all_devices(self):  # 全选设备代码...
    for row in range(self.table.rowCount()):
        checkbox_widget = self.table.cellWidget(row, 0)
        if checkbox_widget:
            checkbox = checkbox_widget.layout().itemAt(0).widget()
            checkbox.setChecked(True)


def toggle_select_all_devices(self):
    """切换全选/取消全选状态"""
    # 添加权限检查
    if not self.check_is_admin():
        QMessageBox.warning(self, "权限不足", "只有管理员可以全选设备,请点击右上角的个人中心登录")
        return
        

    # 获取当前按钮文本
    current_text = self.select_all_button.text()
    
    # 遍历所有行的复选框
    all_checked = True
    for row in range(self.table.rowCount()):
        checkbox_widget = self.table.cellWidget(row, 0)
        if checkbox_widget:
            checkbox = checkbox_widget.layout().itemAt(0).widget()
            if not checkbox.isChecked():
                all_checked = False
                break
    
    # 根据当前状态切换
    for row in range(self.table.rowCount()):
        checkbox_widget = self.table.cellWidget(row, 0)
        if checkbox_widget:
            checkbox = checkbox_widget.layout().itemAt(0).widget()
            checkbox.setChecked(not all_checked)
    
    # 更新按钮文本
    self.select_all_button.setText("取消全选" if not all_checked else "全选")


def apply_filter(self):  # 筛选代码...
    vendor_filter = self.vendor_filter_combo.currentText()
    device_type_filter = self.device_type_filter_combo.currentText()
    host_filter = self.host_filter_input.text().strip().lower()
    ip_filter = self.ip_filter_input.text().strip().lower()
    online_status_filter = self.online_status_filter_combo.currentText()

    # 处理"全部"选项
    if vendor_filter == "全部":
        vendor_filter = ""
    if device_type_filter == "全部":
        device_type_filter = ""
    if online_status_filter == "全部":
        online_status_filter = ""

    # 记录当前的筛选条件
    self.current_filters = {
        "vendor": vendor_filter,
        "device_type": device_type_filter,
        "host": host_filter,
        "ip": ip_filter,
        "online_status": online_status_filter
    }

    self.filtered_indices = [index for index, device in enumerate(self.devices) if
                             (not vendor_filter or vendor_filter == device["vendor"]) and
                             (not device_type_filter or device_type_filter == device["device_type"]) and
                             (not host_filter or host_filter in device["host"].lower()) and
                             (not ip_filter or ip_filter in device["ip"].lower()) and
                             (not online_status_filter or online_status_filter == device["online"])]

    filtered_devices = [self.devices[index] for index in self.filtered_indices]
    self.update_table(filtered_devices)
